﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Oracle.DataAccess.Client;

namespace AlertPoster
{
    class Program
    {
        static void Main(string[] args)
        {
            //args是参数
            //args[0]表示操作类型：-i | -u
            //-i:表示插入
            //-u:表示更新
            //args[1]是字段具体的值，用@分割，也就是说字段的内容不能有@
            //test : -i nd_33959@10.188.122.193@服务器@unix@@OPEN@LDLDFREESPACEPERC@39.00%@Critical@Windows主机(10.188.122.115)的逻辑磁盘(C:)空间剩余率为(39.00%) 告警阀值为(<=90.0%)。@INC000000002917@In Process@2012/10/20 8:38:41
            //test : -u nd_33959@10.188.122.193@服务器@unix@@CLOSED@LDLDFREESPACEPERC@39.00%@Critical@Windows主机(10.188.122.115)的逻辑磁盘(C:)空间剩余率为(39.00%) 告警阀值为(<=90.0%)。@INC000000002917@Closed@2012/10/20 8:50:41
            string fieldNames = ConfigurationManager.AppSettings["fieldNames"];
            string target = ConfigurationManager.AppSettings["target"];

            try
            {
                //Log.OpenLog();

                if (string.IsNullOrEmpty(fieldNames)
                   || string.IsNullOrEmpty(target)
                   )
                {
                    //Log.Info("config missing.");
                    return;
                }

                if (args.Length < 2)
                {
                    Usage();
                    return;
                }
                //Log.Info(args.Length.ToString());
                string valueStr = string.Empty;
                for (int i = 1; i < args.Length; i++)
                {
                    valueStr += args[i] + " ";
                    //Log.Info(args[i]);
                }
                valueStr.TrimEnd(' ');

                string op = args[0];
                string[] values = valueStr.Split('@');//
                string[] fields = fieldNames.Split(',');//
                //Log.Info(valueStr);
                Dictionary<string, string> fieldsDic = new Dictionary<string, string>();
                int count = 0;
                foreach (var f in fields)
                {
                    fieldsDic.Add(f, values[count]);
                    count++;
                }

                OracleDataAccess oda = new OracleDataAccess(target);
                try
                {
                    if (op == "-i")
                    {
                        string sql = "select id from device where";
                        if (string.IsNullOrEmpty(fieldsDic["DeviceIP"]))
                            sql += " identify is null";
                        else
                            sql += " identify = '" + fieldsDic["DeviceIP"] + "'";

                        if (string.IsNullOrEmpty(fieldsDic["DeviceType"]))
                            sql += " and type is null";
                        else
                            sql += " and type = '" + fieldsDic["DeviceType"] + "'";

                        if (string.IsNullOrEmpty(fieldsDic["DeviceObject"]))
                            sql += " and object is null";
                        else
                            sql += " and object = '" + fieldsDic["DeviceObject"] + "'";


                        if (string.IsNullOrEmpty(fieldsDic["DeviceSubObject"]) || fieldsDic["DeviceType"] == "服务器")
                            sql += " and subobject is null";
                        else
                            sql += " and subobject = '" + fieldsDic["DeviceSubObject"] + "'";

                        var deviceid = oda.ExecuteScalar(sql);
                        if (deviceid != null)
                        {
                            int id = Convert.ToInt32(deviceid);
                            string isql = "insert into alert values(:id,:eventid,:deviceid,:status,:parameter,:value,:severity,:msg,:ticketid,:ticketstatus,:timestamp,:createtime,:lastmodifiedtime)";
                            OracleParameter[] ops = new OracleParameter[]{ 
                            new OracleParameter("id",null),
                            new OracleParameter("eventid",fieldsDic["EventId"]),
                            new OracleParameter("deviceid",id),
                            new OracleParameter("status",fieldsDic["Status"]),
                            new OracleParameter("parameter",fieldsDic["Parameter"]),
                            new OracleParameter("value",fieldsDic["Value"]),
                            new OracleParameter("severity",ConvertSeverity(fieldsDic["Severity"])),
                            new OracleParameter("msg",fieldsDic["Msg"]),
                            new OracleParameter("ticketid",fieldsDic["TicketId"]),
                            new OracleParameter("ticketstatus",fieldsDic["TicketStatus"]),
                            new OracleParameter("timestamp",Convert.ToDateTime(fieldsDic["Timestamp"])),
                            new OracleParameter("createtime",DateTime.Now),
                            new OracleParameter("lastmodifiedtime",DateTime.Now)
                        };

                            oda.ExecuteCommand(isql, ops);
                            //Log.Info("Insert OK.");
                        }
                        else
                        {
                            //Log.Info("device not match");
                        }
                    }
                    else if (op == "-u")
                    {
                        string usql = @"update alert set status=:status,parameter=:parameter,value=:value,severity=:severity,
msg=:msg,ticketid=:ticketid,ticketstatus=:ticketstatus,timestamp=:timestamp,lastmodifiedtime=:lastmodifiedtime where eventid=:eventid";
                        OracleParameter[] ops = new OracleParameter[]{ 
                            new OracleParameter("eventid",fieldsDic["EventId"]),
                            new OracleParameter("status",fieldsDic["Status"]),
                            new OracleParameter("parameter",fieldsDic["Parameter"]),
                            new OracleParameter("value",fieldsDic["Value"]),
                            new OracleParameter("severity",ConvertSeverity(fieldsDic["Severity"])),
                            new OracleParameter("msg",fieldsDic["Msg"]),
                            new OracleParameter("ticketid",fieldsDic["TicketId"]),
                            new OracleParameter("ticketstatus",fieldsDic["TicketStatus"]),
                            new OracleParameter("timestamp",Convert.ToDateTime(fieldsDic["Timestamp"])),
                            new OracleParameter("lastmodifiedtime",DateTime.Now)
                        };

                        oda.ExecuteCommand(usql, ops);
                        //Log.Info("Update OK.");
                    }

                }
                catch
                { }
                finally
                {
                    oda.Dispose();
                }
            }
            catch
            { }

            finally
            {
                //Log.CloseLog();
            }
           
        }

        static void Usage()
        {
            Console.WriteLine(@"            //args是参数
                //args[0]表示操作类型：-i | -u
                //-i:表示插入
                //-u:表示更新
                //args[1]是字段具体的值，用@分割，也就是说字段的内容不能有@");
        }

        static int ConvertSeverity(string severity)
        {
            switch (severity.ToLower())
            {
                case "critical":
                    return 2;
                case "warning":
                    return 1;
                case "normal":
                    return 0;
                default:
                    return 0;
            }
        }
    }
}
